// src/pages/publishReview/index.tsx
import React, { useEffect, useRef, useState } from 'react';
import Taro, { useDidShow, useUnload } from '@tarojs/taro';
import { View, Image, Textarea, Text } from '@tarojs/components';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import { observer } from 'mobx-react-lite';
import store from '@/src/store';
import LoadingSpinner from '@/src/components/loadingSpinner';
import { showToast, StatusToast } from '@/src/components/statusToast';
import ArticleEditor, {
  ArticleEditorRef,
  Block, //  引入 Block 类型，便于给 initialBlocks 标注类型
} from '@/src/components/articleEditor';
import RelatePopup from '@/src/components/relatePopup';
import PhotoRecognition from '@/src/components/photoRecognition';
import CommonModal from '@/src/components/commonModal';
import {
  articlePublishFun,
  uploadFileFun,
} from '@/src/common/method/publishFun';
import { blocksToHTML, blocksToPlainText } from '@/src/utils/richText';
import { formatNow } from '@/src/common/method/commonFun';
import { getNetWorkStatus } from '@/src/common/util/util';
import { netWorkErrorInfo } from '@/src/utils/constants';
import { AtInput } from 'taro-ui';

const MAX_TITLE = 35;
const MAX_IMAGES = 9;
let ucUserId = '';
let ucLoginPhone = '';

const PublishArticle = () => {
  const { contentCigar, contentCigarCabinet } = store.publishStore;
  const { province, provinceCode, city, cityCode } = store.commonStore;
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const editorRef = useRef<ArticleEditorRef>(null);
  // 登场层文字
  const [loadingText, setLoadingText] = useState<string>('');
  const [showPopup, setShowPopup] = useState<boolean>(false);
  // 显示识别雪茄页面
  const [showPhotoRecognition, setShowPhotoRecognition] =
    useState<boolean>(false);
  // 保存提示
  const [showSaveFlag, setShowSaveFlag] = useState<boolean>(false);
  // 文章图片（仅作数量与上传状态管理，不直接驱动编辑器）
  const [contentImgUrl, setContentImgUrl] = useState<string[]>([]);
  // 记录本地临时路径 -> 服务器URL 的映射，用于发布时替换
  const imgUrlMapRef = useRef<Record<string, string>>({});

  //  用于草稿恢复
  const [initialBlocks, setInitialBlocks] = useState<Block[] | undefined>(
    undefined
  );
  const [draftLoaded, setDraftLoaded] = useState(false); // 读取草稿后再挂载编辑器，确保 initialBlocks 生效
  const saveOnUnloadRef = useRef(true);
  useDidShow(() => {
    //判断网络状态
    Taro.onNetworkStatusChange(getNetWorkStatus);
  });
  // 单张上传并安全回填
  const uploadOne = async (localPath: string) => {
    const url = await uploadFileFun(localPath, 'file', {
      type: 'wine_internet_community_dynamic',
    });
    // 预览 & 计数用
    setContentImgUrl((prev) => {
      const idx = prev.indexOf(localPath);
      if (idx === -1) return prev;
      const next = [...prev];
      next[idx] = url;
      return next;
    });
    // 映射用于提交替换
    imgUrlMapRef.current[localPath] = url;
    return url;
  };

  //添加图片
  const handleChooseImage = async () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    await editorRef.current?.syncCursorFromNative();
    const remain = MAX_IMAGES - getEditorImageCount();
    if (remain <= 0) {
      showToast('最多只能选 9 张图片');
      return;
    }

    const res = await Taro.chooseImage({
      count: remain,
      sizeType: ['compressed'],
      sourceType: ['camera', 'album'],
    });
    setLoadingText('上传中...');

    const newLocal = res.tempFilePaths;
    setContentImgUrl((prev) => [...newLocal, ...prev]);

    const editor = editorRef.current;
    if (editor) newLocal.forEach((p) => editor.insertImage(p));

    // 并发上限
    const CONCURRENCY = 9;

    const queue = [...newLocal];
    const results: PromiseSettledResult<string>[] = [];
    const workers = new Array(Math.min(CONCURRENCY, queue.length))
      .fill(0)
      .map(async () => {
        while (queue.length) {
          const p = queue.shift()!;
          try {
            const url = await uploadOne(p);
            results.push({
              status: 'fulfilled',
              value: url,
            } as PromiseFulfilledResult<string>);
          } catch (e: any) {
            results.push({
              status: 'rejected',
              reason: e,
            } as PromiseRejectedResult);
            setLoadingText('');
          }
        }
      });

    await Promise.all(workers);
    setLoadingText('');
    if (results.some((r) => r.status === 'rejected')) {
      showToast('部分图片上传失败，可重试上传或删除');
      setLoadingText('');
    }
  };

  // 当前编辑器里的图片数量（从 blocks 里数）
  const getEditorImageCount = () => {
    const blocks = editorRef.current?.getBlocks?.() ?? [];
    return blocks.filter((b: Block) => b.type === 'image').length;
  };

  // 删除关联雪茄
  const deleteRelateCiga = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigar(null);
  };
  // 删除关联雪茄柜
  const deleteRelateCigaCabinet = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    store.publishStore.setContentCigarCabinet(null);
  };

  //  统一检查本地临时路径（提交前校验）
  const isLocalTemp = (u: string) =>
    /^wxfile:\/\//.test(u) || /^https?:\/\/tmp\//.test(u) || /^blob:/.test(u);

  // 组成提交/草稿信息（最小改动：增加 blocks 字段）
  const getDataFun = () => {
    const blocks = editorRef.current?.getBlocks?.() ?? [];
    const resolver = (u: string) => imgUrlMapRef.current?.[u] || u;

    // 富文本 & 纯文本
    const content_text = blocksToPlainText(blocks);
    const contentRich = blocksToHTML(blocks, resolver);

    //  保存 blocks（把图片地址替换为服务器URL，便于下次直接还原）
    const blocksForDraft: Block[] = blocks.map((b) =>
      b.type === 'image' ? { ...b, content: resolver(b.content) } : b
    );
    // 从“当前文档”里提取最终的图片列表（已用 resolver 转成服务器URL）
    const imagesInDoc = blocks
      .filter((b) => b.type === 'image')
      .map((b) => resolver((b as any).content))
      .filter(Boolean);

    return {
      title,
      content: content_text,
      contentRich,
      contentImgUrl: imagesInDoc,
      contentCigar,
      contentCigarCabinet,
      blocks: blocksForDraft,
    };
  };

  // 判断是否有内容需要提示保存（标题/正文/图片/关联产品任一存在）
  const hasChanges = (json: ReturnType<typeof getDataFun>) => {
    return (
      !!json.title?.trim() ||
      !!json.content?.trim() ||
      (json.contentImgUrl?.length ?? 0) > 0 ||
      !!json.contentCigar ||
      !!json.contentCigarCabinet
    );
  };

  // 返回点击事件
  const backClickFun = () => {
    store.commonStore.setShowTabBar(true);

    // 用编辑器当前内容来判断
    const json = getDataFun();
    if (hasChanges(json)) {
      setShowSaveFlag(true); // 弹出“是否保存当前修改？”
    } else {
      // 没有任何有效内容，直接返回且不触发卸载时的自动保存
      saveOnUnloadRef.current = false;
      Taro.navigateBack();
    }
  };

  // 发布
  const handlePublish = () => {
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    } else {
      setLoadingText('正在发布...');
      const json = getDataFun();

      // 阻止未上传完成的图片
      if (
        (json.blocks || []).some(
          (b: Block) => b.type === 'image' && isLocalTemp(b.content)
        )
      ) {
        showToast('有图片未上传完成，请稍后再试', 'error', 2);
        setLoadingText('');
        return;
      }
      if (!json.title) {
        showToast('请添加标题', 'error', 2);
        setLoadingText('');
        return;
      } else if (!json.content) {
        showToast('请添加文章', 'error', 2);
        setLoadingText('');
        return;
      }

      const submitTime = formatNow();
      const params = {
        ucUserId,
        ucLoginPhone,
        province,
        provinceCode,
        city,
        cityCode,
        ...json,
        submitTime,
        contentKind: 'CIGAR',
      };
      articlePublishFun(params)
        .then((res: any) => {
          setLoadingText('');
          if (res.code === '0') {
            setTimeout(() => {
              // 发布成功之后删除保存的草稿
              Taro.removeStorageSync(`articlePublish-${ucUserId}`);
              saveOnUnloadRef.current = false;
              Taro.navigateBack();
              deleteRelateCiga();
              deleteRelateCigaCabinet();
              store.commonStore.setShowTabBar(true);
            }, 3000);
            showToast('已发布，审核中', 'success', 3);
          } else {
            showToast('发布失败', 'error', 3);
          }
        })
        .catch((_) => {
          setLoadingText('');
        });
    }
  };

  // 点击拍照识别的返回事件
  const onBackClickFun = () => {
    setShowPhotoRecognition(false);
  };

  // 保存草稿
  const okClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setLoadingText('保存中...');
    const json = getDataFun();
    Taro.setStorageSync(`articlePublish-${ucUserId}`, JSON.stringify(json));
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
    setLoadingText('');
  };

  // 不保存草稿
  const cancelClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.removeStorageSync(`articlePublish-${ucUserId}`);
    saveOnUnloadRef.current = false;
    Taro.navigateBack();
    deleteRelateCiga();
    deleteRelateCigaCabinet();
  };

  // 取消草稿
  const otherClickFun = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowSaveFlag(false);
  };

  // iOS 左滑/返回时一定会触发
  useUnload(() => {
    store.commonStore.setShowTabBar(true);
    if (!saveOnUnloadRef.current) return;

    const json = getDataFun();
    if (hasChanges(json)) {
      // 仅当真的有内容时才自动保存草稿
      Taro.setStorageSync(`articlePublish-${ucUserId}`, JSON.stringify(json));
    }
  });

  useEffect(() => {
    ucUserId = String(Taro.getStorageSync('userId') ?? '').trim();
    ucLoginPhone = String(Taro.getStorageSync('mobile') ?? '').trim();

    //  读取草稿并设置 initialBlocks（若无则默认）
    try {
      const info = Taro.getStorageSync(`articlePublish-${ucUserId}`);
      if (info) {
        setLoadingText('正在恢复草稿...');
        const json: any = JSON.parse(info);
        setTitle(json.title || '');
        setContent(json.content || '');
        setContentImgUrl(
          Array.isArray(json.contentImgUrl) ? json.contentImgUrl : []
        );
        if (Array.isArray(json.blocks) && json.blocks.length) {
          setInitialBlocks(json.blocks as Block[]);
        } else {
          setInitialBlocks(undefined); // 走编辑器默认空内容
        }
        store.publishStore.setContentCigar(json.contentCigar);
        store.publishStore.setContentCigarCabinet(json.contentCigarCabinet);
      } else {
        setInitialBlocks(undefined);
      }
    } catch {
      setInitialBlocks(undefined);
    } finally {
      setDraftLoaded(true); //  标记草稿已读完，可以挂载编辑器
      setLoadingText('');
    }
    // 退出之前删除雪茄和雪茄柜关联数据
    return () => {
      deleteRelateCiga();
      deleteRelateCigaCabinet();
    };
  }, []);
  //关联产品
  const handleRelateProduct = () => {
    //判断网络状态
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    setShowPopup(true);
  };
  return (
    <View
      className="publish-review-page"
      style={{ paddingTop: `${store.commonStore.pageAreaTop}rpx` }}
    >
      {showPhotoRecognition ? (
        <PhotoRecognition
          okClickFun={() => {}}
          showRecord={false}
          onBackClickFun={onBackClickFun}
        />
      ) : (
        <View>
          {/* 标题区 */}
          <TitleBar showLeftBack={true} title="发文章" onBack={backClickFun} />
          <View className="publish-title">
            <View className="publish" onClick={handlePublish}>
              发布
            </View>
          </View>
          <AtInput
            className="title-input"
            placeholder="给文章添加一个标题吧！ (1~35 字)"
            value={title}
            name="title"
            maxLength={MAX_TITLE}
            onChange={(e: any) => setTitle(e.trim())}
          />
          <View
            className="content-area"
            style={{
              height: `calc(100vh - 210px - ${store.commonStore.pageAreaTop}rpx - ${store.commonStore.safeAreaBottom}rpx)`,
            }}
          >
            <View
              style={{
                height:
                  contentCigar && contentCigarCabinet
                    ? 'calc(100% - 64px)'
                    : contentCigar || contentCigarCabinet
                      ? 'calc(100% - 34px)'
                      : '100%',
              }}
            >
              {/* 正文区：等待草稿读取完成后再挂载，确保 initialBlocks 生效 */}
              {draftLoaded && (
                <ArticleEditor ref={editorRef} initialBlocks={initialBlocks} />
              )}
            </View>
            {(contentCigar || contentCigarCabinet) && (
              <View className="related-container">
                {contentCigar && (
                  <View className="topic-container">
                    <View className="relation">
                      关联雪茄：
                      <Text className="product">
                        {contentCigar.contentCigarBrand}{' '}
                        {contentCigar.contentCigarZh}
                      </Text>
                    </View>
                    <Image
                      src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                      className="deleteRelation"
                      onClick={deleteRelateCiga}
                    ></Image>
                  </View>
                )}
                {contentCigarCabinet && (
                  <View className="topic-container">
                    <View className="relation">
                      关联雪茄柜：
                      <Text className="product">
                        {contentCigarCabinet.contentCigarCabinetZh}{' '}
                        {contentCigarCabinet.contentCigarCabinetBrand}{' '}
                        {contentCigarCabinet.model}
                      </Text>
                    </View>
                    <Image
                      src="https://file.linkcook.cn/image/wineMiniProgram/home/clear.png"
                      className="deleteRelation"
                      onClick={deleteRelateCigaCabinet}
                    ></Image>
                  </View>
                )}
              </View>
            )}
          </View>
          <View className="publish-buttons">
            <View onClick={handleChooseImage}>
              <View className="button-container">
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/addPicture.png"
                  className="bt-icon"
                />
              </View>
              <View className="bt-desc">添加图片</View>
            </View>
            <View>
              <View
                className="button-container"
                onClick={() => {
                  handleRelateProduct();
                }}
              >
                <Image
                  src="https://file.linkcook.cn/image/wineMiniProgram/home/relationPro.png"
                  className="bt-icon"
                />
              </View>
              <View className="bt-desc">关联产品</View>
            </View>
          </View>
          <StatusToast />
          <RelatePopup
            isShow={showPopup}
            onClose={() => {
              setShowPopup(false);
            }}
            takeCigaPhoto={() => {
              Taro.showToast({ title: 'AI识别开发中', icon: 'none' });
              // setShowPopup(false);
            }}
          />
          <CommonModal
            visible={showSaveFlag}
            title="是否保存当前修改？"
            okText="保存草稿"
            okClick={okClickFun}
            cancelText="不保存"
            cancelClick={cancelClickFun}
            otherText="取消"
            otherClick={otherClickFun}
          />
          <LoadingSpinner text={loadingText} />
        </View>
      )}
    </View>
  );
};

export default observer(PublishArticle);
